package com.ciaojian.worker.controller;

import com.ciaojian.core.util.*;
import com.ciaojian.worker.service.WorkerServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * 文件上传接口
 *
 * @author Atlakyn
 */
@Api(tags = "文件上传")
@RestController
@RequestMapping("/upload")
public class UploadController {
    @Resource
    private WorkerServiceImpl workerService;

    @ApiOperation("批量上传图片")
    @PostMapping("/fileUploads")
    public Result multiUpload(HttpServletRequest request) {
        try {
            List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
            Assert.isTrue(files.size() <= 6, "一次性最多上传6个作品");

            for (MultipartFile file : files) {
                InputStream fis = file.getInputStream();
                String picType = FileUtil.getPicType(fis);
                if ("error".equals(picType)) {
                    return Result.error("请上传图片文件");
                }
            }
            String month = new SimpleDateFormat("yyyy-MM").format(new Date());

            // 线上图片路径
            String filePath = "/www/server/chaojian-client/";
//            String filePath = "/Users/oxiny/Download/";
            List<String> fileNames = new LinkedList<>();
            for (MultipartFile multipartFile : files) {
                String beforeFileName = DateUtil.getCurrentDateStr();
                String fileName = multipartFile.getOriginalFilename();
                // 后缀名
                String suffixName = fileName.substring(fileName.lastIndexOf("."));
                File dest = new File(filePath + beforeFileName + suffixName);
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdirs();
                }
                multipartFile.transferTo(dest);
                String prefixPath = "https://www.ciaojian.com/upload/".concat(beforeFileName + suffixName);
                fileNames.add(prefixPath);
                workerService.getBaseMapper().saveImageUpload(prefixPath);
            }
            return Result.ok(fileNames);
        } catch (Exception e) {
            LogUtil.writeErrorLog(e.toString());
            return Result.error("上传失败");
        }
    }
}
